package com.juc;

/**
 * synchronized
 */

public class LockTestArea{
      public static void main(String[] args) {
        // // 同对象
        // Counter counter = new Counter();
        // Thread t1 = new Thread(counter, "t1");
        // Thread t2 = new Thread(counter, "t2");
        // t1.start();
        // t2.start();
        // // 非同对象
        // Counter counter = new Counter();
        // Counter counter1 = new Counter();
        // Thread t1 = new Thread(counter, "t1");
        // Thread t2 = new Thread(counter1, "t2");
        // t1.start();
        // t2.start();

        // 锁对象
        Text text = new Text();
        Thread t1 = new Thread(text, "t1");
        Thread t2 = new Thread(text, "t2");
        t1.start();
        t2.start();
    }
}


class Counter implements Runnable{
    private volatile int count = 0;
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "open start");
        synchronized (this) {
            System.out.println(Thread.currentThread().getName() + " is running");
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println(Thread.currentThread().getName() + ":" + (count++));
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + " is over");
        }
        System.out.println(Thread.currentThread().getName() + "open end");
    }

}

class Text implements Runnable {
    private static String text = new String();

    @Override
    public void run() {
        String t = new String();
        System.out.println(Thread.currentThread().getName() + "open start");
        synchronized (text) {
            System.out.println(Thread.currentThread().getName() + " is running");
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println(Thread.currentThread().getName() + ":" + text + i);
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + " is over");
        }
        System.out.println(Thread.currentThread().getName() + "open end");
    }
}




